package com.pureut.quality.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.constant.Constants;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.DateUtils;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.quality.domain.ConverterManagement;
import com.pureut.quality.domain.ExternalAuditPlan;
import com.pureut.quality.domain.dto.ConverterMqDto;
import com.pureut.quality.domain.dto.CustomerManagementMqDto;
import com.pureut.quality.domain.dto.ExternalAuditPlanDto;
import com.pureut.quality.domain.vo.ExternalAuditPlanVo;
import com.pureut.quality.domain.vo.SubmitVo;
import com.pureut.quality.export.ExternalAuditPlanExport;
import com.pureut.quality.mapper.ConverterManagementMapper;
import com.pureut.quality.mapper.ExternalAuditPlanMapper;
import com.pureut.quality.service.ConverterManagementService;
import com.pureut.quality.service.ExternalAuditPlanService;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.domain.SysUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/***
 * 外审计划管理
 * Author:C
 * Date:2023/01/19 17:15
 * @DESC
 */
@Service
public class ExternalAuditPlanServiceImpl extends ServiceImpl<ExternalAuditPlanMapper, ExternalAuditPlan> implements ExternalAuditPlanService {

    /**
     * 外审计划管理 数据层
     */
    @Resource
    ExternalAuditPlanMapper externalAuditPlanMapper;

    /**
     * 查询外审计划列表
     * @param externalAuditPlanVo
     * @return
     */
    @Override
    public List<ExternalAuditPlanDto> listExternalAuditPlan(ExternalAuditPlanVo externalAuditPlanVo) {
        List<ExternalAuditPlanDto> externalAuditPlanDtos = externalAuditPlanMapper.listExternalAuditPlan(externalAuditPlanVo);
        return externalAuditPlanDtos;
    }

    /**
     * 查看外审计划
     * @param id
     * @return
     */
    @Override
    public ExternalAuditPlanDto getInfo(Long id) {
        ExternalAuditPlanDto info = externalAuditPlanMapper.getInfo(id);
        return info;
    }

    /**
     * 新增外审计划
     * @param externalAuditPlanVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertExternalAuditPlan(ExternalAuditPlanVo externalAuditPlanVo) {
        ExternalAuditPlan externalAuditPlan = new ExternalAuditPlan();
        BeanUtils.copyProperties(externalAuditPlanVo, externalAuditPlan);
        externalAuditPlan.setStatus("1");
        return save(externalAuditPlan);
    }

    /**
     * 修改外审计划
     * @param externalAuditPlanVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateExternalAuditPlan(ExternalAuditPlanVo externalAuditPlanVo) {
        ExternalAuditPlan externalAuditPlan = new ExternalAuditPlan();
        BeanUtils.copyProperties(externalAuditPlanVo, externalAuditPlan);
        externalAuditPlan.setId(externalAuditPlanVo.getId());
        return updateById(externalAuditPlan);
    }

    /**
     * 删除外审计划
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeExternalAuditPlan(String ids) {

        String[] split = ids.split(",");
        List<String> idList = Arrays.asList(split);

        List<ExternalAuditPlan> list = externalAuditPlanMapper.selectList(new QueryWrapper<ExternalAuditPlan>()
                .lambda().in(ExternalAuditPlan::getId, idList));

        for (ExternalAuditPlan plan : list) {
            if (!plan.getStatus().equals("1") && !plan.getStatus().equals("4")){
                throw new GlobalException("当前单据不是待提交和未通过的数据无法删除!");
            }
        }
        return removeBatchByIds(list);
    }

    /**
     * 提交
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitExternalAuditPlan(Long id) {
        ExternalAuditPlan byId = getById(id);
        if (!byId.getStatus().equals("1")){
            throw new GlobalException("当前单据不是待提交，无法提交审核!");
        }
        byId.setStatus("2");
        return updateById(byId);
    }

    /**
     * 审核
     * @param submitVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean examineExternalAuditPlan(SubmitVo submitVo) {
        ExternalAuditPlan byId = getById(submitVo.getId());
        if (!byId.getStatus().equals("2")){
            throw new GlobalException("当前单据不是待提交，无法提交审核!");
        }
        if (submitVo.getAuditState() == 1){
            byId.setStatus("3");
        } else {
            byId.setStatus("4");
        }
        return updateById(byId);
    }

    /**
     * 撤销
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean revokeExternalAuditPlan(Long id) {
        ExternalAuditPlan byId = getById(id);
//        if (!byId.getStatus().equals("1")){
//            throw new GlobalException("当前单据不是待提交，无法提交审核!");
//        }
        byId.setStatus("1");

        return updateById(byId);
    }

    /**
     * 导出外审计划管理
     * @param externalAuditPlanVo
     * @return
     */
    @Override
    public List<ExternalAuditPlanExport> selectAuditPlanExport(ExternalAuditPlanVo externalAuditPlanVo) {
        if (externalAuditPlanVo.getIdStr() != null){
            String idStr = externalAuditPlanVo.getIdStr();
            String[] split = idStr.split(",");
            externalAuditPlanVo.setIds(Arrays.asList(split));
        }
        return externalAuditPlanMapper.selectAuditPlanExport(externalAuditPlanVo);
    }

    /**
     * 导入外审计划
     * @param coCustomer
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importAuditPlan(List<ExternalAuditPlanExport> coCustomer) {
            if (StringUtils.isNull(coCustomer) || coCustomer.size() == 0) {
                throw new GlobalException("导入外审计划管理不能为空！");
            }
            int successNum = 0;
            int failureNum = 0;
            StringBuilder successMsg = new StringBuilder();
            StringBuilder failureMsg = new StringBuilder();

            for (ExternalAuditPlanExport mouldModelExport : coCustomer) {
                ExternalAuditPlan externalAuditPlan = new ExternalAuditPlan();
                try {

                    // 导入审核日期
                    if (mouldModelExport.getApprovedDate() != null){
                        Date date = DateUtils.parseDate(mouldModelExport.getApprovedDate());
                        externalAuditPlan.setApprovedDate(date);
                    }

                    // 导入审核时间
                    if (mouldModelExport.getAuditTime() != null){
                        Date date = DateUtils.parseDate(mouldModelExport.getAuditTime());
                        externalAuditPlan.setAuditTime(date);
                    }

                    BeanUtils.copyProperties(mouldModelExport, externalAuditPlan);
                    externalAuditPlan.setStatus("1");

                    save(externalAuditPlan);
                    successNum++;
                    successMsg.append(successNum).append("、受审组织 ").append(mouldModelExport.getTrialOrganization()).append(" 导入成功");

                } catch (Exception e) {
                    failureNum++;
                    String msg = failureNum + "、受审组织 " + mouldModelExport.getTrialOrganization() + " 导入失败：";
                    failureMsg.append(msg).append(e.getMessage());
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                throw new GlobalException(failureMsg.toString());
            } else {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            }

            return successMsg.toString();
        }

}
